package top.codedance.iotp.server.net.handle.subhandle;

import cd.io.netty.handler.codec.http.FullHttpRequest;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.enums.HttpStatus;
import top.codedance.iotp.server.ServerApplication;
import top.codedance.iotp.server.net.WsServer;
import top.codedance.iotp.server.net.handle.WsChannelHandler;
import top.codedance.iotp.server.net.handle.WsMsgHandler;
import top.codedance.iotp.server.net.handle.subhandle.controller.WsController;
import cd.io.netty.channel.ChannelHandlerContext;
import org.apache.log4j.Logger;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

public class TextWsMsgHandler implements WsMsgHandler {
    private static Logger logger = ServerApplication.getLogger(TextWsMsgHandler.class);

    public void channelRead(final WsChannelHandler wsChannelHandler, String clientId, ChannelHandlerContext channelHandlerContext, FullHttpRequest request, byte[] msg) throws Exception {
        try {
            String data = new String(msg, StandardCharsets.UTF_8);
            final JSONObject jsonObject = JSONObject.parseObject(data);
            String uri = request.uri();
            String[] subUris = uri.split("/");
            jsonObject.put("agreement", subUris[2]);
            Set<Map.Entry<String, WsController>> entries = WsServer.websocketRoutes.entrySet();
            WsController wsController = null;
            for (Map.Entry<String, WsController> entity : entries) {
                if (entity.getKey().equals(subUris[2])) {
                    wsController = entity.getValue();
                    break;
                }
            }
            if (wsController != null) {
                if(jsonObject.containsKey("body")) {
                    wsController.doHandler(wsChannelHandler, clientId, jsonObject);
                }
            } else {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("status", 400);
                jsonObject1.put("message", "Agreement not found.");
                wsChannelHandler.wsSend(clientId, jsonObject1.toJSONString());
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("status", 500);
            jsonObject1.put("message", "server error.");
            wsChannelHandler.wsSend(clientId, jsonObject1.toJSONString());
        }
    }

    public static String response(int statusCode, Object msg, Object data) {
        JSONObject result = new JSONObject();
        result.put("status", statusCode);
        result.put("message", msg);
        result.put("data", data);
        return result.toJSONString();
    }

    public static String okResponse(Object data) {
        return response(HttpStatus.OK.getCode(), "", data);
    }

    public static String errResponse(int statusCode, Object msg) {
        return response(statusCode, msg, null);
    }

    public static String response500(String msg) {
        return errResponse(HttpStatus.INTERNAL_SERVER_ERROR.getCode(), msg);
    }
}